package edu.dayu.demo2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        Selector selector = Selector.open();

        // 绑定一个端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        // 设置为 非阻塞
        serverSocketChannel.configureBlocking(false);

        // 将serverSocketChannel 注册到 selector上 ,并绑定为接受
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            if (selector.select(10000) == 0){
                System.out.println("服务器等待了 10秒，无连接");
                continue;
            }
            // 如果 返回>0 就获取到相关的 selectionKey 集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey selectionKey = keyIterator.next();
                // 根据 key 对应的通道发生的事件做相应的处理
                if (selectionKey.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功");
                    socketChannel.configureBlocking(false);
                    // 将socketChannel 注册到selector，关注事件为OP_READ，同时给socketChannel关联一个Buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (selectionKey.isReadable()){
                    // 通过key反向获取到对应channel
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    // 获取到该channel关联的 buffer
                    ByteBuffer buffer =(ByteBuffer)selectionKey.attachment();
                    channel.read(buffer);
                    System.out.println("form客户端"+ new String(buffer.array()));
                }
                keyIterator.remove();
            }
        }
    }
}
